import {reqGetCode,reqUserRegister,reqUserLogin,reqUserInfo,reqLogout} from '@/api'
const state={code:'',token:localStorage.getItem('TOKEN'),userInfo:{}}
const mutations={
    GETCODES(state,code){
        state.code=code
    },
    USERLOGIN(state,token){
     state.token=token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo=userInfo
    },
    CLEAR(state){
        state.token=''
        state.userInfo={}
        localStorage.removeItem('TOKEN')
    }
}
const actions={
    async getCodes(context,phone){
       let result=await reqGetCode(phone)
       if(result.code==200){
           context.commit('GETCODES',result.data)
           return 'ok'
       }else{
           return Promise.reject(new Error('失败'))
       }
    },
    async userRegister({commit},{phone,password,code}){
        let result=await reqUserRegister(phone,password,code)
        if(result.code==200){
            return "ok"
        }else{
            return Promise.reject(new Error('faile'))
        }
          },
    async userLogin(context,data){
       let result=await reqUserLogin(data)
       if(result.code==200){
           context.commit('USERLOGIN',result.data.token)
           localStorage.setItem('TOKEN',result.data.token)
           return 'ok'
       }else{
           return Promise.reject(new Error('faile'))
       }
        },
    async getUserInfo(context){
      let result=await reqUserInfo()
      if(result.code==200){
          context.commit('GETUSERINFO',result.data)
         return 'ok'
      }else{
          return Promise.reject(new Error('faile'))
      }
    },
    async userLogout(context){
        let result=await reqLogout()
        if(result.code==200){
            context.commit('CLEAR')
           return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
      }
         
}
const getters={}
export default{
    state,
    mutations,
    actions,
    getters
}